<template>
  <div class="reports-container">
    <div class="page-header">
      <h1 class="page-title">候选人报告</h1>
      <p class="page-subtitle">查看所有候选人的面试评估结果</p>
    </div>

    <!-- 筛选区域 -->
    <div class="filters-section">
      <div class="filter-row">
        <div class="filter-item">
          <label>面试名称</label>
          <el-select v-model="filters.interviewName" placeholder="选择面试" clearable>
            <el-option 
              v-for="interview in interviewOptions" 
              :key="interview.value" 
              :label="interview.label" 
              :value="interview.value"
            />
          </el-select>
        </div>
        
        <div class="filter-item">
          <label>岗位</label>
          <el-select v-model="filters.position" placeholder="选择岗位" clearable>
            <el-option 
              v-for="position in positionOptions" 
              :key="position.value" 
              :label="position.label" 
              :value="position.value"
            />
          </el-select>
        </div>
        
        <div class="filter-item">
          <label>能力等级</label>
          <el-select v-model="filters.ability" placeholder="选择能力等级" clearable>
            <el-option label="优秀" value="excellent" />
            <el-option label="良好" value="good" />
            <el-option label="一般" value="average" />
            <el-option label="待提升" value="poor" />
          </el-select>
        </div>
        
        <div class="filter-item">
          <label>面试状态</label>
          <el-select v-model="filters.status" placeholder="选择状态" clearable>
            <el-option label="通过" value="passed" />
            <el-option label="待评估" value="pending" />
            <el-option label="未通过" value="rejected" />
          </el-select>
        </div>
        
        <div class="filter-actions">
          <el-button type="primary" @click="applyFilters">筛选</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 排序和统计 -->
    <div class="control-section">
      <div class="sort-section">
        <span class="sort-label">排序方式：</span>
        <el-radio-group v-model="sortBy" @change="handleSortChange">
          <el-radio-button label="date">面试时间</el-radio-button>
          <el-radio-button label="score">综合得分</el-radio-button>
          <el-radio-button label="name">姓名</el-radio-button>
        </el-radio-group>
        <el-radio-group v-model="sortOrder" @change="handleSortChange">
          <el-radio-button label="desc">降序</el-radio-button>
          <el-radio-button label="asc">升序</el-radio-button>
        </el-radio-group>
      </div>
      
      <div class="stats-section">
        <span class="stats-item">总数：<strong>{{ filteredCandidates.length }}</strong></span>
        <span class="stats-item">通过：<strong>{{ passedCount }}</strong></span>
        <span class="stats-item">通过率：<strong>{{ passRate }}%</strong></span>
      </div>
    </div>

    <!-- 批量操作区域 -->
    <div v-if="selectedCandidates.length > 0" class="batch-actions-section">
      <div class="batch-info">
        <span class="batch-text">已选择 {{ selectedCandidates.length }} 个候选人</span>
        <el-button @click="clearSelection" type="text" size="small">清除选择</el-button>
      </div>
      
      <div class="batch-buttons">
        <el-button 
          type="success" 
          @click="batchApprove('approve')"
          :loading="batchLoading"
        >
          <el-icon><Check /></el-icon>
          批量通过
        </el-button>
        <el-button 
          type="danger" 
          @click="batchApprove('reject')"
          :loading="batchLoading"
        >
          <el-icon><Close /></el-icon>
          批量拒绝
        </el-button>
        <el-button 
          type="primary" 
          @click="batchApprove('follow_ai')"
          :loading="batchLoading"
        >
          <el-icon><Robot /></el-icon>
          跟随AI推荐
        </el-button>
      </div>
    </div>

    <!-- 候选人列表 -->
    <div class="candidates-list">
      <div class="list-header">
        <div class="header-item">
          <el-checkbox 
            v-model="selectAll" 
            @change="handleSelectAll"
            :indeterminate="isIndeterminate"
          >
            全选
          </el-checkbox>
        </div>
        <div class="header-item">候选人信息</div>
        <div class="header-item">面试信息</div>
        <div class="header-item">能力评估</div>
        <div class="header-item">综合得分</div>
        <div class="header-item">状态</div>
        <div class="header-item">操作</div>
      </div>
      
      <div 
        v-for="candidate in paginatedCandidates" 
        :key="candidate.id"
        class="candidate-row"
      >
        <div class="candidate-select">
          <el-checkbox 
            v-model="selectedCandidates" 
            :label="candidate.id"
            @change="handleSelectCandidate"
          />
        </div>
        
        <div class="candidate-info" @click="viewReport(candidate.id)">
          <el-avatar :src="candidate.avatar" :size="48">
            {{ candidate.name.charAt(0) }}
          </el-avatar>
          <div class="info-content">
            <h4 class="candidate-name">{{ candidate.name }}</h4>
            <p class="candidate-phone">{{ candidate.phone }}</p>
            <p class="candidate-email">{{ candidate.email }}</p>
          </div>
        </div>
        
        <div class="interview-info" @click="viewReport(candidate.id)">
          <div class="interview-name">{{ candidate.interviewName }}</div>
          <div class="interview-position">{{ candidate.position }}</div>
          <div class="interview-date">{{ formatDate(candidate.interviewDate) }}</div>
        </div>
        
        <div class="ability-assessment" @click="viewReport(candidate.id)">
          <div class="ability-item">
            <span class="ability-label">逻辑思维</span>
            <el-progress 
              :percentage="candidate.abilities.logic" 
              :color="getAbilityColor(candidate.abilities.logic)"
              :stroke-width="6"
            />
          </div>
          <div class="ability-item">
            <span class="ability-label">专业技能</span>
            <el-progress 
              :percentage="candidate.abilities.professional" 
              :color="getAbilityColor(candidate.abilities.professional)"
              :stroke-width="6"
            />
          </div>
          <div class="ability-item">
            <span class="ability-label">沟通表达</span>
            <el-progress 
              :percentage="candidate.abilities.communication" 
              :color="getAbilityColor(candidate.abilities.communication)"
              :stroke-width="6"
            />
          </div>
        </div>
        
        <div class="score-section" @click="viewReport(candidate.id)">
          <div class="overall-score">{{ candidate.overallScore }}</div>
          <div class="score-label">综合得分</div>
        </div>
        
        <div class="status-section" @click="viewReport(candidate.id)">
          <el-tag 
            :type="getStatusType(candidate.status)"
            class="status-tag"
          >
            {{ getStatusText(candidate.status) }}
          </el-tag>
        </div>
        
        <div class="actions-section">
          <el-button type="primary" size="small" @click.stop="viewReport(candidate.id)">
            查看报告
          </el-button>
          <el-button type="text" size="small" @click.stop="downloadReport(candidate.id)">
            下载报告
          </el-button>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="filteredCandidates.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check, Close, Robot } from '@element-plus/icons-vue'
import { hrSparkApi } from '@/services/api'

export default {
  name: 'ReportsView',
  components: {
    Check,
    Close,
    Robot
  },
  setup() {
    const router = useRouter()
    
    // 筛选条件
    const filters = ref({
      interviewName: '',
      position: '',
      ability: '',
      status: ''
    })
    
    // 排序条件
    const sortBy = ref('date')
    const sortOrder = ref('desc')
    
    // 分页
    const currentPage = ref(1)
    const pageSize = ref(20)
    
    // 批量操作
    const selectedCandidates = ref([])
    const selectAll = ref(false)
    const isIndeterminate = ref(false)
    const batchLoading = ref(false)

    // 筛选选项
    const interviewOptions = ref([
      { label: '前端开发工程师面试', value: 'frontend-interview' },
      { label: '后端开发工程师面试', value: 'backend-interview' },
      { label: '全栈开发工程师面试', value: 'fullstack-interview' },
      { label: '产品经理面试', value: 'product-manager-interview' }
    ])
    
    const positionOptions = ref([
      { label: '前端开发工程师', value: 'frontend' },
      { label: '后端开发工程师', value: 'backend' },
      { label: '全栈开发工程师', value: 'fullstack' },
      { label: '产品经理', value: 'product-manager' },
      { label: 'UI/UX设计师', value: 'designer' }
    ])
    
    // 候选人数据
    const candidates = ref([
      {
        id: 1,
        name: '张三',
        phone: '13800138000',
        email: 'zhangsan@example.com',
        avatar: '',
        interviewName: '前端开发工程师面试',
        position: '前端开发工程师',
        interviewDate: '2024-01-15',
        abilities: {
          logic: 85,
          professional: 90,
          communication: 78
        },
        overallScore: 84,
        status: 'passed'
      },
      {
        id: 2,
        name: '李四',
        phone: '13800138001',
        email: 'lisi@example.com',
        avatar: '',
        interviewName: '后端开发工程师面试',
        position: '后端开发工程师',
        interviewDate: '2024-01-14',
        abilities: {
          logic: 88,
          professional: 85,
          communication: 80
        },
        overallScore: 84,
        status: 'pending'
      },
      {
        id: 3,
        name: '王五',
        phone: '13800138002',
        email: 'wangwu@example.com',
        avatar: '',
        interviewName: '全栈开发工程师面试',
        position: '全栈开发工程师',
        interviewDate: '2024-01-13',
        abilities: {
          logic: 70,
          professional: 75,
          communication: 68
        },
        overallScore: 71,
        status: 'rejected'
      },
      {
        id: 4,
        name: '赵六',
        phone: '13800138003',
        email: 'zhaoliu@example.com',
        avatar: '',
        interviewName: '产品经理面试',
        position: '产品经理',
        interviewDate: '2024-01-12',
        abilities: {
          logic: 92,
          professional: 88,
          communication: 90
        },
        overallScore: 90,
        status: 'passed'
      },
      {
        id: 5,
        name: '孙七',
        phone: '13800138004',
        email: 'sunqi@example.com',
        avatar: '',
        interviewName: '前端开发工程师面试',
        position: '前端开发工程师',
        interviewDate: '2024-01-11',
        abilities: {
          logic: 80,
          professional: 85,
          communication: 82
        },
        overallScore: 82,
        status: 'passed'
      }
    ])
    
    // 计算属性
    const filteredCandidates = computed(() => {
      let filtered = candidates.value.slice()
      
      // 应用筛选条件
      if (filters.value.interviewName) {
        filtered = filtered.filter(c => c.interviewName === filters.value.interviewName)
      }
      if (filters.value.position) {
        filtered = filtered.filter(c => c.position === filters.value.position)
      }
      if (filters.value.ability) {
        const abilityThreshold = {
          excellent: 85,
          good: 70,
          average: 60,
          poor: 0
        }
        filtered = filtered.filter(c => c.overallScore >= abilityThreshold[filters.value.ability])
      }
      if (filters.value.status) {
        filtered = filtered.filter(c => c.status === filters.value.status)
      }
      
      // 应用排序
      filtered.sort((a, b) => {
        let aValue, bValue
        
        switch (sortBy.value) {
          case 'date':
            aValue = new Date(a.interviewDate)
            bValue = new Date(b.interviewDate)
            break
          case 'score':
            aValue = a.overallScore
            bValue = b.overallScore
            break
          case 'name':
            aValue = a.name
            bValue = b.name
            break
          default:
            aValue = a.interviewDate
            bValue = b.interviewDate
        }
        
        if (sortOrder.value === 'desc') {
          return bValue > aValue ? 1 : -1
        } else {
          return aValue > bValue ? 1 : -1
        }
      })
      
      return filtered
    })
    
    const paginatedCandidates = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return filteredCandidates.value.slice(start, end)
    })
    
    const passedCount = computed(() => {
      return filteredCandidates.value.filter(c => c.status === 'passed').length
    })
    
    const passRate = computed(() => {
      if (filteredCandidates.value.length === 0) return 0
      return Math.round((passedCount.value / filteredCandidates.value.length) * 100)
    })
    
    // 方法
    const applyFilters = () => {
      currentPage.value = 1
    }
    
    const resetFilters = () => {
      filters.value = {
        interviewName: '',
        position: '',
        ability: '',
        status: ''
      }
      currentPage.value = 1
    }
    
    const handleSortChange = () => {
      currentPage.value = 1
    }
    
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
    }
    
    const formatDate = (dateString) => {
      return new Date(dateString).toLocaleDateString('zh-CN')
    }
    
    const getAbilityColor = (percentage) => {
      if (percentage >= 85) return '#67c23a'
      if (percentage >= 70) return '#e6a23c'
      if (percentage >= 60) return '#f56c6c'
      return '#909399'
    }
    
    const getStatusType = (status) => {
      const typeMap = {
        'passed': 'success',
        'pending': 'warning',
        'rejected': 'danger'
      }
      return typeMap[status] || 'info'
    }
    
    const getStatusText = (status) => {
      const textMap = {
        'passed': '通过',
        'pending': '待评估',
        'rejected': '未通过'
      }
      return textMap[status] || '未知'
    }
    
    const viewReport = (candidateId) => {
      router.push(`/hr/evaluation/${candidateId}`)
    }
    
    const downloadReport = (candidateId) => {
      console.log('下载报告:', candidateId)
      // 实现下载逻辑
    }

    // 批量操作逻辑
    const handleSelectCandidate = () => {
      const total = filteredCandidates.value.length
      const selected = selectedCandidates.value.length
      
      if (selected === 0) {
        selectAll.value = false
        isIndeterminate.value = false
      } else if (selected === total) {
        selectAll.value = true
        isIndeterminate.value = false
      } else {
        selectAll.value = false
        isIndeterminate.value = true
      }
    }

    const handleSelectAll = (val) => {
      selectedCandidates.value = val ? filteredCandidates.value.map(c => c.id) : []
      isIndeterminate.value = false
    }

    const clearSelection = () => {
      selectedCandidates.value = []
      selectAll.value = false
      isIndeterminate.value = false
    }

    const batchApprove = async (action) => {
      if (selectedCandidates.value.length === 0) {
        ElMessage.warning('请选择要批量操作的候选人')
        return
      }
      
      // 获取操作文本
      const actionText = {
        'approve': '批量通过',
        'reject': '批量拒绝',
        'follow_ai': '跟随AI推荐'
      }[action]
      
      const reasonText = {
        'approve': '批量审批通过',
        'reject': '批量审批拒绝',
        'follow_ai': '跟随AI推荐（70分以上通过）'
      }[action]

      try {
        await ElMessageBox.confirm(
          `确定要${actionText} ${selectedCandidates.value.length} 个候选人吗？`,
          '批量操作确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        batchLoading.value = true
        
        // 调用真正的API
        const response = await hrSparkApi.batchApproval(
          selectedCandidates.value,
          action,
          reasonText
        )
        
        if (response.success) {
          ElMessage.success(`${actionText}成功，处理了${response.data.updated_count}个报告`)
          
          // 更新本地候选人状态
          const updatedCandidates = candidates.value.map(candidate => {
            if (selectedCandidates.value.includes(candidate.id)) {
              let newStatus = candidate.status
              if (action === 'approve') {
                newStatus = 'passed'
              } else if (action === 'reject') {
                newStatus = 'rejected'
              } else if (action === 'follow_ai') {
                // 跟随AI推荐：70分以上通过
                newStatus = candidate.overallScore >= 70 ? 'passed' : 'rejected'
              }
              return { ...candidate, status: newStatus }
            }
            return candidate
          })
          
          candidates.value = updatedCandidates
          clearSelection()
          
        } else {
          ElMessage.error(`${actionText}失败`)
        }
        
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量操作失败:', error)
          ElMessage.error(`${actionText}失败`)
        }
      } finally {
        batchLoading.value = false
      }
    }
    
    onMounted(() => {
      console.log('候选人报告列表加载完成')
    })
    
    return {
      filters,
      sortBy,
      sortOrder,
      currentPage,
      pageSize,
      interviewOptions,
      positionOptions,
      filteredCandidates,
      paginatedCandidates,
      passedCount,
      passRate,
      applyFilters,
      resetFilters,
      handleSortChange,
      handleSizeChange,
      handleCurrentChange,
      formatDate,
      getAbilityColor,
      getStatusType,
      getStatusText,
      viewReport,
      downloadReport,
      selectedCandidates,
      selectAll,
      isIndeterminate,
      batchLoading,
      handleSelectCandidate,
      handleSelectAll,
      clearSelection,
      batchApprove
    }
  }
}
</script>

<style scoped>
.reports-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 2rem;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 8px;
}

.page-subtitle {
  color: var(--text-secondary);
  font-size: 1rem;
}

.filters-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-row {
  display: flex;
  gap: 16px;
  align-items: end;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  flex-direction: column;
  min-width: 160px;
}

.filter-item label {
  font-size: 14px;
  color: var(--text-secondary);
  margin-bottom: 4px;
}

.filter-actions {
  display: flex;
  gap: 8px;
}

.control-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.sort-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.sort-label {
  font-size: 14px;
  color: var(--text-secondary);
}

.stats-section {
  display: flex;
  gap: 20px;
}

.stats-item {
  font-size: 14px;
  color: var(--text-secondary);
}

.batch-actions-section {
  background: white;
  padding: 16px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  border-left: 4px solid #409eff;
}

.batch-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: var(--text-secondary);
}

.batch-text {
  font-weight: 600;
  color: var(--text-primary);
}

.batch-buttons {
  display: flex;
  gap: 8px;
}

.batch-buttons .el-button {
  padding: 8px 16px;
  font-size: 14px;
}

.candidates-list {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.list-header {
  display: grid;
  grid-template-columns: 0.5fr 2fr 1.5fr 2fr 1fr 1fr 1.5fr;
  gap: 16px;
  padding: 16px 20px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  font-weight: 600;
  color: var(--text-secondary);
}

.header-item {
  font-size: 14px;
  display: flex;
  align-items: center;
}

.candidate-row {
  display: grid;
  grid-template-columns: 0.5fr 2fr 1.5fr 2fr 1fr 1fr 1.5fr;
  gap: 16px;
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  transition: background-color 0.3s;
}

.candidate-row:hover {
  background: #f5f7fa;
}

.candidate-row:last-child {
  border-bottom: none;
}

.candidate-select {
  display: flex;
  align-items: center;
  justify-content: center;
}

.candidate-info {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
}

.info-content {
  flex: 1;
}

.candidate-name {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 4px;
}

.candidate-phone,
.candidate-email {
  font-size: 12px;
  color: var(--text-secondary);
  margin: 0;
}

.interview-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
  cursor: pointer;
}

.interview-name {
  font-size: 14px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 4px;
}

.interview-position {
  font-size: 12px;
  color: var(--text-secondary);
  margin-bottom: 2px;
}

.interview-date {
  font-size: 12px;
  color: var(--text-secondary);
}

.ability-assessment {
  display: flex;
  flex-direction: column;
  gap: 8px;
  cursor: pointer;
}

.ability-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.ability-label {
  font-size: 12px;
  color: var(--text-secondary);
  min-width: 60px;
}

.score-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.overall-score {
  font-size: 24px;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 4px;
}

.score-label {
  font-size: 12px;
  color: var(--text-secondary);
}

.status-section {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.actions-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.actions-section .el-button {
  width: 100%;
  padding: 6px 12px;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .batch-actions-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .batch-buttons {
    width: 100%;
    justify-content: flex-start;
  }
  
  .list-header,
  .candidate-row {
    grid-template-columns: 0.5fr 1.5fr 1fr 1.5fr 0.8fr 0.8fr 1fr;
  }
  
  .ability-assessment {
    gap: 4px;
  }
  
  .ability-label {
    min-width: 40px;
    font-size: 10px;
  }
}

@media (max-width: 768px) {
  .batch-buttons {
    flex-direction: column;
    width: 100%;
  }
  
  .list-header,
  .candidate-row {
    grid-template-columns: 0.3fr 1fr 0.8fr 1fr 0.6fr 0.6fr 0.8fr;
    gap: 8px;
    padding: 12px;
  }
  
  .candidate-name {
    font-size: 14px;
  }
  
  .candidate-phone,
  .candidate-email {
    font-size: 10px;
  }
  
  .overall-score {
    font-size: 18px;
  }
  
  .actions-section .el-button {
    padding: 4px 8px;
    font-size: 10px;
  }
}
</style> 